package com.sayimo.maker.commons.utils;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;

import com.sayimo.framework.common.MessageObject;
import com.sayimo.framework.exception.ServiceException;

/**
 * @Project: sayimoWeixinApi
 * @ClassName: HttpUtils
 * @Description: 
 * @Author: 王瑞清
 * @Date: 日期：2015年9月9日 时间：下午9:44:12
 * @Version 1.0.0
 */
public class HttpUtils {

	private static Log logger = LogFactory.getLog(HttpUtils.class);

	/** 
	* @Title: saveUrlImageToDisk 
	* @Description: 获取网络上图片并保存在本地
	* @param urlPath
	* @param filePath
	* @throws IOException
	* @return void
	*/ 
	public static void saveUrlImageToDisk(String urlPath, String filePath)
			throws IOException {
		InputStream inputStream = getInputStream(urlPath);
		byte[] data = new byte[1024];
		int len = 0;
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream(filePath);
			while ((len = inputStream.read(data)) != -1) {
				fileOutputStream.write(data, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (Exception e) {
					logger.debug(e);
				}
			}
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (Exception e) {
					logger.debug(e);
				}
			}
		}
	}

	
	
	/** 
	* @Title: getInputStream 
	* @Description: 获取图片流
	* @param urlPath
	* @throws IOException
	* @return InputStream
	*/ 
	public static InputStream getInputStream(String urlPath) throws IOException {
		InputStream inputStream = null;
		HttpURLConnection httpURLConnection = null;
		try {
			URL url = new URL(urlPath);
			if (url != null) {
				httpURLConnection = (HttpURLConnection) url.openConnection();
				httpURLConnection.setConnectTimeout(3000);
				httpURLConnection.setDoInput(true);
				httpURLConnection.setRequestMethod("GET");
				int responseCode = httpURLConnection.getResponseCode();
				if (responseCode == 200) {
					inputStream = httpURLConnection.getInputStream();
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return inputStream;

	}
	
	/**
	 * 
	 * @MethodName getMethod
	 * @Description get方式提交
	 * 
	 * @author chenpy
	 * @date 2015年12月15日 上午11:02:39
	 * @param 
	 * @return String
	 * @VERSION 1.0.0
	 */
	public static String getMethod(String url){
		InputStream inputStream = null;
		HttpGet request = null;
		try {
			CloseableHttpClient client = HttpClients.createDefault();
			request = new HttpGet(url);
			HttpResponse response = client.execute(request);
			inputStream = response.getEntity().getContent();
			StringBuilder sBuffer = new StringBuilder();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				sBuffer.append(str);
			}
			return sBuffer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			IOUtils.closeQuietly(inputStream);
			request.releaseConnection();
		}
		return null;
	}
	
	public static String URLPost(String url, Map<String, String> params, String enc){ 
		logger.info(url);
		String EMPTY = "";  
        String response = EMPTY;          
        PostMethod postMethod = null;  
        try {  
            postMethod = new PostMethod(url);  
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc); 
            //将表单的值放入postMethod中  
            Set<String> keySet = params.keySet();  
            for(String key : keySet){  
                String value = params.get(key);  
                postMethod.addParameter(key, value);  
            }  
            HttpClient client = new HttpClient();
            //执行postMethod  
            int statusCode = client.executeMethod(postMethod);  
            if(statusCode == HttpStatus.SC_OK) {  
                response = postMethod.getResponseBodyAsString();  
            }else{  
                logger.error("响应状态码 = " + postMethod.getStatusCode());  
            }  
        }catch(IOException e){  
        	logger.error("发生网络异常", e);  
            e.printStackTrace();  
        }finally{  
            if(postMethod != null){  
                postMethod.releaseConnection();  
                postMethod = null;  
            }  
        }  
          
        return response;  
    }  
	/**
	 * 
	 * @MethodName postMethod
	 * @Description post提交
	 * 
	 * @author chenpy
	 * @date 2015年12月15日 上午10:55:45
	 * @param url
	 * @param param参数
	 * @return String
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({"rawtypes" })
	public static String postMethod(String url, Map param){
		
		InputStream inputStream = null;
		HttpPost request = null;
		try {
			CloseableHttpClient client = HttpClients.createDefault();
			request = new HttpPost(url);
			request.addHeader(new BasicHeader("Accept", "application/json"));
			request.addHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"));
			
			StringEntity entity = new StringEntity(JSONUtil.writeValueAsString(param), "UTF-8");
			request.setEntity(entity);
			
			HttpResponse response = client.execute(request);
			
			inputStream = response.getEntity().getContent();
			
			StringBuffer sBuffer = new StringBuffer();
			
//			byte[] bt = new byte[1024];
//			int i = inputStream.read(bt);
//			while (i > 0) {
//				sBuffer.append(new String(bt, 0, i, Charset.forName("UTF-8")));
//				i = inputStream.read(bt);
//			}
			
			
			 BufferedReader in = new BufferedReader(new InputStreamReader(inputStream,Charset.forName("UTF-8")));
			    String line = "";
			    while ((line = in.readLine()) != null){
			    	sBuffer.append(line);
			    }
			    
			    
			return sBuffer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			request.releaseConnection();
		}
		
		return null;
	}
	
	/**
	 * 
	  * @package com.sayimo.school.mall.util
	  * @author chenpy
	  * @Title:  
	  * @Description: 
	  * @param 
	  * @throws ServiceException
	  * @return MessageObject
	  * @date 2016年3月18日
	 */
	@SuppressWarnings("unchecked")
	public static MessageObject postMethod(String action,String body) throws MalformedURLException,IOException{
		InputStream is = null;
		
		try {
			MessageObject messageObject = new MessageObject();
			String result="";
			 
			 URL url = new URL(action);
			 HttpURLConnection http = (HttpURLConnection) url.openConnection(); 
			 http.setRequestMethod("POST"); 
			 http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
			 http.setDoOutput(true); 
			 http.setDoInput(true);
			 http.connect();
			 
			 OutputStream os= http.getOutputStream(); 
			 os.write(body.getBytes("UTF-8"));//传入参数 
			 os.flush();
			 os.close();
			 
			 is =http.getInputStream();
			 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
			 String line = null;
			 StringBuffer sBuffer = new StringBuffer();
			 while ((line = bufferedReader.readLine()) != null) {
				sBuffer.append(line);
			 }
			 
			 result=sBuffer.toString();
			 System.out.println("result=============="+result);
			 logger.info(result);
			 messageObject.setObject(JSONUtil.readValueToMap(result));
			 return messageObject;
		} catch (Exception e) {
			logger.error(e);
		} finally{
			IOUtils.closeQuietly(is);
		}
		return null;
	}

	public static String postMethod_URLForm(String url, Map paramMap){
		StringBuilder builder = new StringBuilder();
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost request = new HttpPost(url);
		HttpEntity entity;
		InputStream inputStream = null;
		try {
			List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
			if (paramMap != null && paramMap.size() > 0) {
				Set keys = paramMap.keySet();
				for (Object object : keys) {
					String key = (String) object;
					BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key, String.valueOf(paramMap.get(key)));
					parameters.add(basicNameValuePair);
				}
			}
			logger.info("parameters = " + JSONUtil.writeValueAsString(parameters));
			entity = new UrlEncodedFormEntity(parameters, "UTF-8");
			request.setEntity(entity);
			CloseableHttpResponse closeableHttpResponse = client.execute(request);
			if (closeableHttpResponse.getStatusLine().getStatusCode() == 200) {
				inputStream = closeableHttpResponse.getEntity().getContent();
				BufferedReader in = new BufferedReader(new InputStreamReader(inputStream,Charset.forName("UTF-8")));
			    String line = "";
			    while ((line = in.readLine()) != null){
			    	builder.append(line);
			    }
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			IOUtils.closeQuietly(client);
		}
		
		return builder.toString();
	}
}
